<?php
/**
 * (actions)
 */
namespace App\Admin\Actions\Reimburse;

use App\Models\Reimburse\ReimbursePaid;
use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
class ApplyOnce extends BatchAction
{
    public $name = '一次性返款申请';

    public function handle(Collection $collection)
    {
        try{
            $count = 0;
            foreach ($collection as $model) {
                DB::beginTransaction();
                $rp = ReimbursePaid::query()
                    ->where('reimburse_no',$model->reimburse_no)
                    ->where('order_by',1)
                    ->where('apply_status',1)
                    ->first();
                if(!$rp){
                    DB::rollBack();
                    continue;
                }
                if(!$rp->paid_amount){
                    DB::rollBack();
                    continue;
                }
                $rp->apply_status = 2;
                $flag1 = $rp->save();
                if(!$flag1){
                    DB::rollBack();
                    continue;
                }
                $model->apply_status = 2;
                $model->audit_status = 1;
                $flag2 = $model->save();
                if(!$flag2){
                    DB::rollBack();
                }else{
                    $count++;
                    DB::commit();
                }
            }
            return $this->response()->success("成功申请{$count}条记录！")->refresh();
        }catch (\Exception $e){
            report($e);
            return $this->response()->error('系统异常！');
        }
    }
}
